package com.fognl.core.net.handler;

import java.util.ArrayList;
import java.util.List;

/** Basic NetworkHandler implementation. */
public class NetworkHandlerImpl implements NetworkHandler
{
	/** Our worker manager. */
	private WorkerManager manager;
	
	public NetworkHandlerImpl()
	{
		super();
	}
	
	/** Initiate a request for some data. The specified listener will be called when the request is processed, or 
	 * an error occurs.
	 */
	public RequestHandle startRequest(Request request, ResponseListener listener) throws NetworkHandlerException
	{
		RequestHandle handle = new RequestHandle(request, listener);
		
		// Queue this task.
		getWorkerManager().queue(handle);
		// Return the handle to the caller so it can cancel it later if needed.
		return handle;
	}

	/** Cancel the request associated with the specified handle. */
	public NetworkHandler cancelRequest(RequestHandle handle) throws NetworkHandlerException
	{
		try {
			getWorkerManager().cancelRequest(handle);
		}
		catch(Exception ex)
		{
			throw new NetworkHandlerException(ex.getMessage(), ex);
		}
		
		return this;
	}
	
	/** Return the pending requests in a list. */
	public List<RequestHandle> getPendingRequests()
	{
		return new ArrayList<RequestHandle>(getWorkerManager().getPendingRequests().keySet());
	}
	
	private WorkerManager getWorkerManager()
	{
		if(manager == null)
			manager = new WorkerManager();
		return manager;
	}
}
